package com.ruoyi.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.li.work.mapper.SysDeptMapper;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.li.work.mapper.SysUserRoleMapper;
import com.ruoyi.teaching.domain.*;
import com.ruoyi.teaching.domain.vo.PlatformSCollectVO;
import com.ruoyi.teaching.mapper.PlatformCCourseMapper;
import com.ruoyi.teaching.mapper.PlatformCSpecialtyMapper;
import com.ruoyi.teaching.mapper.PlatformSCollectMapper;
import com.ruoyi.teaching.mapper.PlatformUVirtualMapper;
import com.ruoyi.teaching.service.PlatformSCollectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2024-06-24
 */
@Service
public class PlatformSCollectServiceImpl extends ServiceImpl<PlatformSCollectMapper, PlatformSCollect> implements PlatformSCollectService {

    @Autowired
    private PlatformSCollectMapper platformSCollectMapper;

    @Autowired
    private PlatformCCourseMapper platformCCourseMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PlatformUVirtualMapper platformUVirtualMapper;

    @Autowired
    private PlatformCSpecialtyMapper platformCSpecialtyMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     *
     * @param pageNum           页码
     * @param pageSize          条数
     * @param collectType       收藏类别（0虚拟仿真，1在线授课）
     * @param choose            筛选条件（虚拟仿真下0全部，1PC，2VR，3AR，4MR。在线授课下0全部，1专业授课，2云课堂）
     * @return
     */
    @Override
    public AjaxResult listOwn(Integer pageNum, Integer pageSize, Integer collectType, Integer choose) {
        int userId = SecurityUtils.getUserId().intValue();

        // 构建查询条件
        QueryWrapper<PlatformSCollect> queryWrapper = new QueryWrapper<>();
        if (collectType != null) {
            queryWrapper.eq("collect_type", collectType);
        }
        queryWrapper.eq("person_id", userId);

        // 执行查询
        List<PlatformSCollect> allPlatformSCollects = platformSCollectMapper.selectList(queryWrapper);

        List<PlatformSCollectVO> platformSCollectVOS = new ArrayList<>();

        // 遍历查询结果并进行处理
        for (PlatformSCollect collect : allPlatformSCollects) {
            PlatformSCollectVO platformSCollectVO = new PlatformSCollectVO();
            BeanUtils.copyProperties(collect, platformSCollectVO);

            if (collect.getCollectType() == 0) {
                // 虚拟仿真处理
                Integer virtualId = collect.getProjectId();
                PlatformUVirtual platformUVirtual = platformUVirtualMapper.selectById(virtualId);

                String virtualType = platformUVirtual.getVirtualType();
                Integer[] virtualTypeArray = UniversalUtil.stringToArray(virtualType, Integer::valueOf, Integer.class);
                if (virtualTypeArray == null || virtualTypeArray.length == 0) {
                    // 如果虚拟类型为空数组，跳过当前记录
                    continue;
                }

                // 根据条件筛选
                if (choose != null) {
                    int targetValue = -1; // 默认无效值
                    switch (choose) {
                        case 1: targetValue = 0; break;
                        case 2: targetValue = 1; break;
                        case 3: targetValue = 3; break;
                        case 4: targetValue = 2; break;
                        default: break;
                    }
                    if (targetValue != -1 && !ArrayUtils.contains(virtualTypeArray, targetValue)) {
                        continue;
                    }
                }

                // 设置虚拟仿真相关信息
                platformSCollectVO.setProjectName(platformUVirtual.getVirtualName());
                platformSCollectVO.setPersonName(platformUVirtual.getCreateBy());
                platformSCollectVO.setCollectImage(platformUVirtual.getResourceImage());
                platformSCollectVO.setVirtualType(virtualTypeArray);

                Integer professionalCategoryId = platformUVirtual.getProfessionalCategoryId();
                PlatformCSpecialty platformCSpecialty = platformCSpecialtyMapper.selectById(professionalCategoryId);
                if (platformCSpecialty != null) {
                    platformSCollectVO.setDeptName(platformCSpecialty.getSpecialtyName());
                }
                platformSCollectVO.setTopDeptName(platformUVirtual.getUploadPersonSchool());

            } else if (collect.getCollectType() == 1) {
                // 在线授课处理
                Integer courseId = collect.getProjectId();
                PlatformCCourse platformCCourse = platformCCourseMapper.selectById(courseId);

                // 根据选择条件筛选课程
                if (choose != null) {
                    if (choose == 1 && platformCCourse.getCourseVisible() != 1) {
                        continue;
                    } else if (choose == 2 && platformCCourse.getCourseVisible() != 0) {
                        continue;
                    }
                }

                // 设置课程相关信息
                platformSCollectVO.setProjectName(platformCCourse.getCourseName());
                platformSCollectVO.setCollectImage(platformCCourse.getCourseImage());

                // 设置专业信息
                Integer professionalCategoryId = platformCCourse.getProfessionalCategoryId();
                PlatformCSpecialty platformCSpecialty = platformCSpecialtyMapper.selectById(professionalCategoryId);
                if (platformCSpecialty != null) {
                    platformSCollectVO.setDeptName(platformCSpecialty.getSpecialtyName());
                }

                // 设置用户信息
                platformSCollectVO.setPersonName(platformCCourse.getCreateBy());

                // 获取顶级部门信息
                long createId = platformCCourse.getCreateId().longValue();
                String topLevelSchoolName = UniversalUtil.findTopLevelSchoolName(sysUserRoleMapper, sysDeptMapper, sysUserMapper, createId);
                if (!"".equals(topLevelSchoolName)) {
                    platformSCollectVO.setTopDeptName(topLevelSchoolName);
                }
            }

            platformSCollectVOS.add(platformSCollectVO);
        }

        // 进行分页处理
        int total = platformSCollectVOS.size();
        int start = (pageNum - 1) * pageSize;
        int end = start + pageSize;

        // 确保分页索引安全
        if (start >= total) {
            start = total;
        }
        if (end > total) {
            end = total;
        }

        // 分页后的子列表
        List<PlatformSCollectVO> paginatedList = platformSCollectVOS.subList(start, end);

        // 创建新的分页对象并复制属性
        Page<PlatformSCollectVO> collectVOPage = new Page<>(pageNum, pageSize);
        collectVOPage.setRecords(paginatedList);
        collectVOPage.setTotal(total);

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", collectVOPage);
    }


    @Override
    public AjaxResult insertPlatformSCollect(PlatformSCollect platformSCollect) {
        UniversalCreateUpdate create = UniversalUtil.getCreateUpdate(sysUserMapper);
        //一门课课程或虚拟仿真只能收藏一次
        QueryWrapper<PlatformSCollect> platformSCollectQueryWrapper = new QueryWrapper<>();
        Integer collectType = platformSCollect.getCollectType();
        platformSCollectQueryWrapper.eq("collect_type", collectType);
        platformSCollectQueryWrapper.eq("project_id", platformSCollect.getProjectId());
        Integer id = create.getId();
        platformSCollectQueryWrapper.eq("person_id", id);
        int count = Math.toIntExact(platformSCollectMapper.selectCount(platformSCollectQueryWrapper));
        if (count > 0) {
            return new AjaxResult(HttpStatus.ERROR, "您已收藏过该"+(collectType == 0 ? "虚拟仿真" : "课程")+"，无需再次收藏");
        }
        platformSCollect.setCreateId(id);
        platformSCollect.setCreateTime(DateUtils.getNowDate());
        platformSCollect.setCreateBy(create.getName());
        platformSCollect.setPersonId(id);

        int insert = platformSCollectMapper.insert(platformSCollect);
        if (insert > 0) {
            return new AjaxResult(HttpStatus.SUCCESS, "恭喜你，收藏成功啦，要及时学习噢~~");
        } else {
            return new AjaxResult(HttpStatus.ERROR, "收藏失败");
        }
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult deleteCollectByIds(Long[] ids) {
        int length = ids.length;
        int deleteCount = platformSCollectMapper.deleteBatchIds(Arrays.asList(ids));
        if (deleteCount == length) {
            return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
        } else {
            return new AjaxResult(HttpStatus.ERROR, "删除失败");
        }
    }

    /**
     * @param collectType   收藏类型（0虚拟仿真，1在线课程）
     * @param projectId     收藏的项目id
     * @return
     */
    @Override
    public AjaxResult deleteCollectInFront(Integer collectType, Integer projectId) {
        int personId = SecurityUtils.getUserId().intValue();
        QueryWrapper<PlatformSCollect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("person_id", personId);
        queryWrapper.eq("collect_type", collectType);
        queryWrapper.eq("project_id", projectId);
        int delete = platformSCollectMapper.delete(queryWrapper);
        if (delete > 0) {
            return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
        } else {
            return new AjaxResult(HttpStatus.ERROR, "您暂时未收藏该"+(collectType == 0 ? "虚拟仿真" : "课程"));
        }
    }
}
